package com.ruoyi.project.system.controller;

import com.ruoyi.framework.security.RegisterLogin;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.security.RegisterBody;
import com.ruoyi.framework.security.service.SysRegisterService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.system.service.ISysConfigService;

/**
 * 注册验证
 */
@RestController
public class SysRegisterController extends BaseController {
    @Autowired
    private SysRegisterService registerService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysConfigService configService;

    @PostMapping("/register")
    public AjaxResult register(@RequestBody RegisterBody user) {    // MGZ TODO 2025/3/13:注册处
        if (!("true".equals(configService.selectConfigByKey("sys.account.registerUser")))) {
            return error("当前系统没有开启注册功能！");
        }
        String registerParemt = user.getParent();
        String parent = user.getParent();
        Long roleId = 2l;
        while (StringUtils.isNotEmpty(parent)) {
            roleId = 3l;
            SysUser sysUser = userService.selectUserById(Long.parseLong(parent));
            if (sysUser == null || StringUtils.isEmpty(sysUser.getParent())) {
                break;
            } else {
                parent = sysUser.getParent();
            }
        }

        user.setRegisterParemt(registerParemt);
        user.setParent(parent);
        user.setRoleId(roleId);

        RegisterLogin register = registerService.register(user);
        return register.getRegister() ? success(register.getResultStr()) : error(register.getResultStr());
    }
}
